package com.ly.honor.interceptor;

import com.alibaba.fastjson.JSON;
import com.ly.honor.exception.HonorException;
import com.ly.honor.util.RedisUtil;
import com.ly.honor.util.Result;
import com.ly.honor.util.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 李某人
 * @Date 2023/3/21 21:41
 * @Version 1.0
 */
public class CaptchaInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        var cookies = request.getCookies();
        String captchaId = "";
        for(Cookie cookie :cookies){
            if("captchaId".equals(cookie.getName())){
                captchaId = cookie.getValue();
            }
        }
        var code = request.getHeader("code");
        System.out.println(code);
        if(code.equals(redisUtil.get(captchaId))){
            return true;
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(Result.fail(ResultEnum.CAPTCHA_ERROR)));
        return false;
    }


}
